// utils/loading.ts
import Taro from '@tarojs/taro'

class LoadingService {
  private loadingCount = 0
  private isShowing = false

  // 显示 loading
  show(options?: {
    title?: string
    duration?: number
    icon?: 'loading' | 'success' | 'error' | 'none'
    mask?: boolean
  }) {
    this.loadingCount++

    // 如果已经在显示，先关闭再重新打开（Taro 不支持直接更新）
    if (this.isShowing) {
      this._hide()
    }

    const config = {
      title: options?.title || '加载中...',
      icon: options?.icon || 'loading',
      duration: options?.duration || 0, // 0 表示不自动关闭
      mask: options?.mask ?? true,
      ...options
    }

    this._show(config)
  }

  private _show(config: any) {
    Taro.showLoading({
      title: config.title,
      mask: config.mask
    })
    this.isShowing = true
  }

  // 隐藏 loading
  hide() {
    this.loadingCount--

    // 确保计数不会为负数
    if (this.loadingCount <= 0) {
      this.loadingCount = 0
      this._hide()
    }
  }

  private _hide() {
    Taro.hideLoading()
    this.isShowing = false
  }

  // 强制隐藏所有 loading（重置状态）
  hideAll() {
    this.loadingCount = 0
    this._hide()
  }

  // 获取当前 loading 计数
  getLoadingCount(): number {
    return this.loadingCount
  }

  // 便捷方法：显示带文字的 loading
  showText(title: string = '加载中...') {
    this.show({ title })
  }

  // 显示成功 toast
  showSuccess(title: string = '操作成功', duration: number = 2000) {
    Taro.showToast({
      title,
      icon: 'success',
      duration,
      mask: true
    })
  }

  // 显示错误 toast
  showError(title: string = '操作失败', duration: number = 2000) {
    Taro.showToast({
      title,
      icon: 'error',
      duration,
      mask: true
    })
  }

  // 显示警告 toast
  showWarning(title: string = '警告', duration: number = 2000) {
    Taro.showToast({
      title,
      icon: 'none',
      duration,
      mask: true
    })
  }
}

// 创建单例实例
export const loadingService = new LoadingService()

// 导出便捷方法
export const showGlobalLoading = (title?: string) => loadingService.show({ title })
export const hideGlobalLoading = () => loadingService.hide()
export const hideAllLoading = () => loadingService.hideAll()
